package cn.ewan.cloud.tenant.data.router.example.controller;

import cn.ewan.cloud.common.support.Log;
import cn.ewan.cloud.common.support.utils.AsyncUtil;
import cn.ewan.cloud.tenant.data.router.core.business.context.TenantContext;
import cn.ewan.cloud.tenant.data.router.core.common.util.TenantLog;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.concurrent.ExecutionException;

/**
 * @author lgh
 * @date 2022/12/13 18:12
 */
@RestController
public class TestController {

    @Resource
    TestFeign testFeign;

    @Resource
    AsyncTest asyncTest;


    @GetMapping("find/tenant/appname")
    public String getTenantApp(Integer appId) {
        return testFeign.routeTest(appId);
    }


    @GetMapping("find/tenant/async/appname")
    public String getTenantAppAsync(Integer appId) throws ExecutionException, InterruptedException {
        Log.NORMAL.info("method=getTenantAppAsync,threadId={},threadName={}", Thread.currentThread().getId(), Thread.currentThread().getName());
        String s = asyncTest.routeAsyncTest1(appId).get();
        return s;
    }


    @GetMapping("find/tenant/async/util/clear")
    public String getTenantAsyncUtilClear() throws ExecutionException, InterruptedException {
        TenantLog.log("method=getTenantAppAsync");
        AsyncUtil.run(()->{
            TenantLog.log("asyncUtil");
        });
        //清理一下租户信息, 再测试下子线程是否还保留
        TenantContext.removeTenant();
        AsyncUtil.run(()->{
            TenantLog.log("asyncUtil");
        });
        return "ok";
    }

    @GetMapping("find/tenant/async/Executor/clear")
    public String getTenantExecutorAsyncClear() throws ExecutionException, InterruptedException {
        TenantLog.log("method=getTenantAppAsync");
        String s = asyncTest.asyncExecutorRestore().get();
        //清理一下租户信息, 再测试下子线程是否还保留
        TenantContext.removeTenant();
        s = asyncTest.asyncExecutorRestore().get();
        return s;
    }


    @GetMapping("find/tenant/async/thread/clear")
    public String getAsyncThreadClear(Integer appId) throws ExecutionException, InterruptedException {
        Thread a = new Thread(() -> {
            TenantLog.log("test child thread is restore");
            try {
                Thread.sleep(3000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            TenantLog.log("test child thread is restore");
        });
        a.setName("test");
        a.start();
        //清理一下租户信息, 再测试下子线程是否还保留
        TenantContext.removeTenant();
//        Thread.sleep(5000);
        return "finish";
    }


    @GetMapping("find/tenant/govUserEwanA")
    public String govUserEwanA(Integer id) {
        return testFeign.govUserEwanA(id);
    }
}
